package com.hisense.ovcloud.commons.configs.vertx;

import com.hisense.ovcloud.commons.configs.vertx.annotation.VerticleRegister;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.spi.VerticleFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import javax.annotation.PostConstruct;
import java.util.Arrays;

@Configuration
@ComponentScan("com.hisense.ovcloud")
@Order(100)
public class VertxDeployer implements ApplicationContextAware {
    private ApplicationContext context;

    @Autowired
    private DeploymentOptions options;

    @Autowired
    private Vertx vertx;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    @PostConstruct
    public void initVerticles() {
        VerticleFactory verticleFactory = context.getBean(EDVerticleFactory.class);
        vertx.registerVerticleFactory(verticleFactory);
        String[] verticleBeanNames = context.getBeanNamesForAnnotation(VerticleRegister.class);
        Arrays.stream(verticleBeanNames)
                .forEach(verticle -> {
                    vertx.deployVerticle(verticleFactory.prefix() + ":" + context.getBean(verticle).getClass().getName(),
                            options);
                });
    }
}
